<?php

namespace farm\utils;

use farm\traits\BaseUtils;
use farm\traits\DynamicParamsSingleton;
use Medoo\Medoo;

class Db
{
    use DynamicParamsSingleton, BaseUtils;
    CONST STATE_NORMAL = 0;
    CONST STATE_DEL = 9;
    protected Medoo $db;
    public function __construct()
    {
        $this->db = new Medoo([
            'type' => 'mysql',
            'database' => env('DB_FARM_DATABASE'),
            'host' => env('DB_HOST'),
            'port' => env('DB_PORT'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'charset' => 'utf8mb4',
        ]);
    }

    public static function getNormalState()
    {
        return static::STATE_NORMAL;
    }
    public function id(): ?string
    {
        return $this->db->id();
    }
    public function _select($table, $where, $fields = '*')
    {
        return $this->db->select($table, $fields, $where);
    }

    public function _insert($table, $values)
    {
        $this->db->insert($table, $values);
        return $this->db->id();
//        var_dump($this->db->log());
    }

    public static function getTableName():string
    {
        $class = explode("\\", static::class);
        $className = end($class);
        return self::uncamelize($className);
    }

    public static function select($where, $fields = '*')
    {
        $table = static::getTableName();
        return self::getInstance()->_select($table, $where, $fields);
    }
    public static function insert($values): ?string
    {
        $table = static::getTableName();
        return self::getInstance()->_insert($table, $values);
    }


    public static function test() {
        return __CLASS__;
    }

}
